package gen

import (
	"bytes"
	"fmt"
	"io/ioutil"

	"gopkg.in/goyy/goyy.v0/util/strings"
)

var mapperTemplate = `<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="{{.Package}}.{{.DaoPkg}}{{moduleCrePkg .}}.{{camel .Bean}}Dao">
	<sql id="{{aamel .Bean}}Columns">
		{{range $i,$v:= .Cloums}}{{if gt $i 0}},{{end}}a.{{$v.ColumnName}} AS "{{tfname .ColumnName}}"{{end}}
	</sql>
	
	<select id="get" resultType="{{.Package}}.{{.BeanPkg}}{{moduleCrePkg .}}.{{camel .Bean}}">
		SELECT 
		<include refid="{{aamel .Bean}}Columns" /> 
		FROM {{.Bean}} a WHERE a.id = #{id}
	</select>
	
	<select id="findList" resultType="{{.Package}}.{{.BeanPkg}}{{moduleCrePkg .}}.{{camel .Bean}}">
		SELECT 
		<include refid="{{aamel .Bean}}Columns" /> 
		FROM {{.Bean}} a
		<where>
			a.deleted = 0{{range $i,$v:= .Cloums}}
			<if test="{{tfname .ColumnName}} != null and {{tfname .ColumnName}} != ''">
				AND a.{{.ColumnName}} = #{ {{tfname .ColumnName}}} 
			</if>{{end}}
		</where>
		<choose>
			<when test="page !=null and page.orderBy != null and page.orderBy != ''">
				ORDER BY ${page.orderBy}
			</when>
			<otherwise>
				ORDER BY a.update_date DESC
			</otherwise>
		</choose>
	</select>
	
	<select id="findAllList" resultType="{{.Package}}.{{.BeanPkg}}{{moduleCrePkg .}}.{{camel .Bean}}">
		SELECT 
		<include refid="{{aamel .Bean}}Columns" /> 
		FROM {{.Bean}} a
		<where>
			a.deleted = 0
		</where>
		<choose>
			<when test="page !=null and page.orderBy != null and page.orderBy != ''">
				ORDER BY ${page.orderBy}
			</when>
			<otherwise>
				ORDER BY a.update_date DESC
			</otherwise>
		</choose>
	</select>
	
	<insert id="insert" useGeneratedKeys="true" keyProperty="id">
		INSERT INTO {{.Bean}}({{range $i,$v:= .Cloums}}{{if gt $i 0}},{{end}}{{$v.ColumnName}}{{end}}) 
		VALUES ({{range $i,$v:= .Cloums}}{{if gt $i 0}},{{end}}#{ {{tfname .ColumnName}}}{{end}})
	</insert>
	
	<update id="update">
		UPDATE {{.Bean}} SET 
		{{range $i,$v:= .Cloums}}{{if ne $v.ColumnName "id"}}{{if gt $i 1}},{{end}}{{$v.ColumnName}} = #{ {{tfname .ColumnName}}}{{end}}{{end}}
		WHERE id = #{id}
	</update>
	
	<update id="delete">
		UPDATE {{.Bean}} SET deleted = 1 WHERE id = #{id}
	</update>
</mapper>
`

func GenMapper(genModules []Module) {
	fmt.Println("开始生成 Mapper...")
	for _, genModule := range genModules {
		if genModule.IsGenMapper {
			var project = genModule.SProject
			var cloums = genModule.Cloums
			var dir = PackageDir(genModule, "mapper")
			MkdirAll(dir)
			for tableName, cloums := range cloums {
				buf := bytes.Buffer{}
				var tempData = NewTempData(tableName, cloums, project, genModule)
				templ := NewTmpl(mapperTemplate)
				templ.Execute(&buf, tempData)
				fmt.Println(buf.String())
				err := ioutil.WriteFile(dir+"\\"+strings.Camel(tempData.Bean)+"Mapper.xml", buf.Bytes(), 0755)
				if err != nil {
					fmt.Println(err.Error())
				}
			}
		}
	}
}
